package com.zbc.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.zbc.annotations.AuthCheck;
import com.zbc.config.MinioConfig;
import com.zbc.constants.UserConstant;
import com.zbc.domain.common.Result;
import com.zbc.enums.ErrorCode;
import com.zbc.exception.BusinessException;
import com.zbc.manager.CosManager;
import com.zbc.manager.MinioManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2025/9/2 13:55
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/file")
@Api(tags = "文件模块 (测试)")
public class FileController {
    private final CosManager cosManager;
    private final MinioManager minioManager;
    private final MinioConfig minioConfig;

    /**
     * 文件上传测试（腾讯云）
     *
     * @param multipartFile 本地文件
     * @return 文件上传路径
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload/test")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<String> uploadFileTest(@RequestPart("file") MultipartFile multipartFile) {
        // 1. 拼接文件路径, 构造文件夹
        String originalFilename = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s", originalFilename);
        File file = null;
        try {
            // 创建临时文件, 前缀是 filePath, 后缀默认是 .tmp
            file = File.createTempFile(filePath, null);
            // 将文件保存到服务器指定位置, 要求参数默认不存在才创建
            multipartFile.transferTo(file);
            // 上传文件到 COS
            cosManager.putObject(filePath, file);
            return Result.success(filePath);
        } catch (Exception e) {
            log.error("upload error", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            if (file != null) {
                boolean deleted = file.delete();
                if (!deleted) {
                    log.error("文件删除失败");
                }
            }
        }
    }

    /**
     * 文件上传测试（minio）
     *
     * @param multipartFile 本地文件
     * @return 文件上传路径
     */
    @ApiOperation(value = "文件上传(minio)")
    @PostMapping("/upload/minio")
    public Result<String> uploadFile4Minio(@RequestPart("file") MultipartFile multipartFile) {
        // 1. 拼接文件路径, 构造文件夹
        String originalFilename = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s", originalFilename);
        File file = null;
        try {
            // 创建临时文件, 前缀是 filePath, 后缀默认是 .tmp
            file = File.createTempFile(filePath, null);
            // 将文件保存到服务器指定位置, 要求参数默认不存在才创建
            multipartFile.transferTo(file);
            // 上传文件到 COS
            minioManager.putObject(minioConfig.getBucketName(), filePath, file);
            return Result.success(filePath);
        } catch (Exception e) {
            log.error("upload error", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            if (file != null) {
                boolean deleted = file.delete();
                if (!deleted) {
                    log.error("文件删除失败");
                }
            }
        }
    }

    /**
     * 文件下载测试
     *
     * @param filePath 文件路径
     * @param response 设置响应
     */
    @ApiOperation(value = "文件下载")
    @PostMapping("/download/test")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public void downloadTest(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            // 获取文件
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInput = cosObject.getObjectContent();
            // 处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("file download error, filepath = {}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }
    }
}
